<template>
<div>
    <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span>设备管理</span>
            <el-button @click="openAddDeviceDialog" style="float: right; padding: 3px 0" type="text">新增设备</el-button>
        </div>

        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="查询条件">
                <el-input placeholder="查询条件"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary">查询</el-button>
            </el-form-item>
            <!-- <el-button type="primary">新建</el-button> -->
        </el-form>
        <el-table :data="devicePage.list" v-loading.body="devicePage.listLoading" element-loading-text="拼命加载中" border fit highlight-current-row>
            <el-table-column prop="name" label="姓名">
            </el-table-column>
            <el-table-column prop="model" label="型号">
            </el-table-column>
            <el-table-column prop="createTime" label="添加时间">
            </el-table-column>
            <el-table-column prop="departmentId" label="所属部门">
            </el-table-column>
            <el-table-column prop="addressId" label="存放地">
            </el-table-column>
            <el-table-column prop="price" label="价格">
            </el-table-column>
            <el-table-column prop="typeId" label="类别">
            </el-table-column>
            <el-table-column prop="count" label="总数">
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="100">
                <template slot-scope="scope">
                    <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
                    <el-button type="text" size="small">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 弹窗 -->
    <!-- 传感器管理对话框 -->
    <el-dialog title="添加设备" :visible.sync="deviceFormDialog.visible" :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form ref="deviceForm" label-width="80px" :model="deviceFormDialog.deviceForm" :rules="deviceFormDialog.deviceFormRules">
            <el-form-item label="设备名称" prop="comments">
                <el-input v-model="deviceFormDialog.deviceForm.comments"></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="comments">
                <el-input-number v-model="num1" @change="handleChange" :min="1" :max="10" label="数量"></el-input-number>
            </el-form-item>
            <el-form-item label="价格" prop="comments">
                <el-input-number v-model="num1" @change="handleChange" :min="1" :max="10" label="价格"></el-input-number>
            </el-form-item>
            <el-form-item label="允许使用" prop="comments">
                <el-checkbox-group>
                  <el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox>
                  <el-checkbox label="地推活动" name="type"></el-checkbox>
                  <el-checkbox label="线下主题活动" name="type"></el-checkbox>
                  <el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="类型选择" prop="specificationToken">
                <el-select placeholder="类型" v-model="deviceFormDialog.deviceForm.specificationToken">
                    <el-option
                        v-for="item in dependencyList.specificationList"
                        :label="item.name"
                        :key="item.name"
                        :value="item.token">
                        <img style="float: left; height:26px" :src="item.assetImageUrl">
                        <span style="float: left">{{ item.name }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.assetName }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属部门" prop="specificationToken">
                <el-select placeholder="类型" v-model="deviceFormDialog.deviceForm.specificationToken">
                    <el-option
                        v-for="item in dependencyList.specificationList"
                        :label="item.name"
                        :key="item.name"
                        :value="item.token">
                        <img style="float: left; height:26px" :src="item.assetImageUrl">
                        <span style="float: left">{{ item.name }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.assetName }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="存放地" prop="specificationToken">
                <el-select placeholder="类型" v-model="deviceFormDialog.deviceForm.specificationToken">
                    <el-option
                        v-for="item in dependencyList.specificationList"
                        :label="item.name"
                        :key="item.name"
                        :value="item.token">
                        <img style="float: left; height:26px" :src="item.assetImageUrl">
                        <span style="float: left">{{ item.name }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.assetName }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="deviceFormDialog.visible = false">取 消</el-button>
            <el-button type="primary" v-if="deviceFormDialog.isCreate" @click="addDevice('deviceForm')">确 定</el-button>
            <el-button type="primary" v-else @click="saveDeviceEdit('deviceForm')">确 定</el-button>
        </div>
    </el-dialog>
</div>
</template>

<script>
import { getDevices } from '@/api/items/devices'
export default {
  name: 'Devices',
  data () {
    return {
      devicePage: {
        // 主题数据，设备分页列表，这个地方与list同级的还有分页的其他参数信息
        list: [],
        listLoading: true
      },
      deviceFormDialog: {
        // 设备表单弹框
        visible: false, // 控制是否显示
        isCreate: true,
        deviceForm: {
          metadata: {},
          specification: '',
          siteToken: ''
        },
        deviceFormRules: {
          // 增加或编辑表单校验规则
          comments: [
            { required: true, message: '请输入设备名称', trigger: 'blur' }
          ],
          specificationToken: [
            { required: true, message: '请选择分类', trigger: 'change' }
          ]
        }
      },
      dependencyList: {
        // 依赖列表，主要是下拉框相关
        specificationList: []
      },
      serachForm: {
        // 不需要可见属性，其他规则与增加编辑表单一致
      },
      tableData: []
    }
  },
  mounted () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      this.listLoading = true
      const params = {
        current: 1,
        size: 10
      }
      getDevices(params).then(response => {
        console.log(response)
        this.devicePage.list = response.data.content.records
        this.devicePage.listLoading = false
      })
    },

    viewData: function (token) {
      this.$router.push('/devices/sensors/' + token)
    },
    openEditDeviceDialog: function (index) { // 打开设备编辑模态框
      swHttp.get('/api/devices/' + this.devicePage.list[index].hardwareId, { params: { 'includeSpecification': false, 'includeSite': false }}).then(res => {
        this.deviceFormDialog.isCreate = false
        this.deviceFormDialog.deviceForm = res.data
      })
      this.deviceFormDialog.visible = true
    },
    openAddDeviceDialog: function () { // 打开设备增加模态框
      this.deviceFormDialog.deviceForm = {}
      this.deviceFormDialog.visible = true
      this.deviceFormDialog.isCreate = true
    },
    saveDeviceEdit: function (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          // 提交设备信息
          const hardwareId = this.deviceFormDialog.deviceForm.hardwareId
          swHttp.put('/api/devices/' + hardwareId, this.deviceFormDialog.deviceForm).then(res => {
            // 如果添加成功，那么关闭当前对话框，给出提示，并重新请求数据
            getList(this.listQuery).then(response => {
              this.devicePage.list = response.data.results
              this.devicePage.listLoading = false
            })
            this.deviceFormDialog.visible = false
            this.$notify({
              title: '成功',
              message: '设备信息修改成功',
              type: 'success'
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addDevice: function (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          // 提交设备信息
          this.deviceFormDialog.deviceForm.siteToken = 'bb105f8d-3150-41f5-b9d1-db04965668d3'
          this.deviceFormDialog.deviceForm.hardwareId = new Date().getTime()
          swHttp.post('/api/devices', this.deviceFormDialog.deviceForm).then(res => {
            // 如果添加成功，那么关闭当前对话框，给出提示，并重新请求数据
            getList(this.listQuery).then(response => {
              this.devicePage.list = response.data.results
              this.devicePage.listLoading = false
            })
            this.deviceFormDialog.visible = false
            this.$notify({
              title: '成功',
              message: '新增设备成功',
              type: 'success'
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    deleteDevice: function (index) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const hardwareId = this.devicePage.list[index].hardwareId
        swHttp.delete('/api/devices/' + hardwareId, this.deviceFormDialog.deviceForm).then(res => {
          // this.$notify({
          //   title: "成功",
          //   message: "设备删除成功",
          //   type: "success"
          // });
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 启用设备
    assign: function (index) {
      const assignment = {
        assignmentType: 'Unassociated',
        deviceHardwareId: this.devicePage.list[index].hardwareId,
        metadata: {}
      }
      swHttp.post('/api/assignments', assignment).then(res => {
        if (res.data.status == 'Active') {
          getList(this.listQuery).then(response => {
            this.devicePage.list = response.data.results
            this.devicePage.listLoading = false
          })
          this.$notify({
            title: '成功',
            message: '设备开启成功',
            type: 'success'
          })
        }
      })
    }
  }
}
</script>
